import {
	getVersion,
	getDownloadApp
} from '@/api/index.js';
import baseURL from "@/utils/baseURL";

// #ifdef APP-PLUS
export const hotUpdate = () => {
	let version, isUpdate, forceUpdate
	// 獲取本機APP版本號應用名等相關信息
	plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
		/*
		uni.request({
			url: '',
			data: {
				version: widgetInfo.version,
				name: widgetInfo.name
			},
			success: (res) => {
				// 後端將進行版本號比對，上傳版本號小於服務器號data.update為true，下發地址
				var data = res.data.data
				id(data.update && data.wgtUrl) {
					// 開始下載後端下發wgt包
					uni.downloadFile({
						url: data.wgtUrl,
						success: (downloadRes) => {
							uni.showToast({
								title: '開始更新下載',
								icon: 'none',
								duration: 2000
							})
							if (downloadRes.statusCode === 200) {
								// 進行自動安裝
								plus.runtime.install(downloadRes.tempFilePath, {
									force: false
								}, function() {
									// 安裝成功後重啟應用
									plus.runtime.restart()
								}, function() {
									uni.showToast({
										title: '安裝失敗',
										icon: 'error'
									})
								})
							}
						},
						fail: (res) => {
							uni.showToast({
								title: '下載失敗',
								icon: 'error',
								duration: 2000
							})
						}
					})
				}
			}
		})
		*/

		version = widgetInfo.versionCode
		getVersion().then(res => {
			forceUpdate = res.data.appIsNeed
			if (res.data.appVersionCode !== version) {
				isUpdate = true
			} else {
				isUpdate = false
			}

			goToUpdate(isUpdate, forceUpdate)
		})
	})
}

export const goToUpdate = (isUpdate, forceUpdate) => {
	const system = plus.os.name
	if (isUpdate) {
		getDownloadApp().then(res => {
			const downloadUrl = baseURL + res.data
			uni.showModal({
				title: '更新提示',
				content: '發信新版本，請立即更新！',
				showCancel: !forceUpdate,
				confirmText: '立即更新',
				success: (res) => {
					if (res.confirm) {
						if (system === 'Android') {
							plus.runtime.openURL(downloadUrl, () => {})
						} else if (system === 'iOS') {
							goToAppStoreForUpdate()
						}
					}
				}
			})
		})
	}
}

export const goToAppStoreForUpdate = () => {
	const appleId = ''
	const appStoreUrl = `items-apps://itunes.apple.com/cn/app/id${appleId}?mt=8`
	plus.runtime.launchApplication({
		action: appStoreUrl,
		success: () => {},
		fail: (err) => {
			uni.showToast({
				title: err.message,
				icon: 'none'
			})
		}
	})
}

// #endif